package com.netease.contract.service;

import com.netease.contract.domain.LoanMapper;
import com.netease.contract.domain.TBContractMapper;
import com.netease.contract.dto.NosResponseDto;
import com.netease.contract.model.Loan;
import com.netease.contract.model.LoanCriteria;
import com.netease.contract.model.TBContract;
import com.netease.contract.model.TBContractCriteria;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by alva on 18/4/21.
 */
@Service
@Slf4j
public class ContractDownloadService {

    @Resource
    private TBContractMapper tBContractMapper;

    @Resource
    private LoanMapper loanMapper;

    @Resource
    private RestTemplate restTemplate;

//    @Resource
//    private NosFileSystem nosFileSystem;


    private String userName = "wyxd";
    private String password = "wyxd_cjbk";
    private String host = "127.0.0.1";
    private int port = 8802;

    private SftpUploader sftpUploader;

    private String credit_upload_path = "/home/ftpuser/hszjyw/wyxd/";

    public void process(String month, String startDate, String endDate, Long lastId) throws Exception {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            return;
        }
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
        DateTime startDay = formatter.parseDateTime(startDate);
        DateTime endDay = formatter.parseDateTime(endDate);

        DateTimeFormatter dtfOut = DateTimeFormat.forPattern("yyyyMM");
        String day = dtfOut.print(startDay);
        Date begin = startDay.withTime(0, 0, 0, 0).toDate();
        Date end = endDay.withTime(23, 59, 59, 999).toDate();
//        log.info("startDate "+startDate);

        String path = credit_upload_path + "wydkht/" + month + "/"; // 目标文件名
//        String localPath = localPath_changjiang + month + "/";
//        File file = new File(localPath);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
        List<String> list = Arrays.asList("1", "3", "5", "6", "9");
        LoanCriteria cond = new LoanCriteria();
        if (null != lastId) {
            cond.createCriteria().andSettleTimeBetween(begin, end).andRaiseRuleIdIn(list).andIdGreaterThan(lastId);
        }else{
            cond.createCriteria().andSettleTimeBetween(begin, end).andRaiseRuleIdIn(list);
        }
        List<Loan> loanList = loanMapper.selectByExample(cond);

        if (!CollectionUtils.isEmpty(loanList)) {
            log.info("loan.size" + loanList.size());
            sftpUploader = new SftpUploader();
            sftpUploader.setHost(host);
            sftpUploader.setPassword(password);
            sftpUploader.setPort(port);
            sftpUploader.setUserName(userName);
            try {
                sftpUploader.connect();
                if (!sftpUploader.isDirExist(path)) {
                    log.info("sftp path not exist,mkdir path" + path);
                    sftpUploader.createDirs(path);
                }
                for (Loan loan : loanList) {
                    try {
                        processLoan(loan, path);
                    } catch (Exception e) {
                        log.error("", e);
                    }
                }
            } catch (Exception e) {
                log.error("", e);
                throw e;
            } finally {
                sftpUploader.close();
            }

        }

    }

    private void processLoan(Loan loan, String path) throws Exception {

        TBContractCriteria contractCriteria = new TBContractCriteria();
        contractCriteria.createCriteria().andLoanIdEqualTo(loan.getId());
        List<TBContract> tbContracts = tBContractMapper.selectByExample(contractCriteria);
        if (CollectionUtils.isEmpty(tbContracts)) {
            return;
        }
        TBContract tbContract = tbContracts.get(0);
        InputStream input = null;
        try {
            if (tbContract.getTemplateCode() != null && tbContract.getTemplateCode().startsWith("WYXD")) {
                log.info("download from pbs,contract.serail" + tbContract.getSerial());
                NosResponseDto responseDto = getNosResponseDto(tbContract.getApplyNo());
                if (responseDto.getSuccessed()) {
                    input = downloadFile(responseDto.getResult().getNosPublicUrl());
                }
            } else {
//                String fileUrl = nosFileSystem.generateUrl(tbContract.getSerial(), FileType.ALL,10000);
                log.info("contract templateCode not start with WYXD,download from NOS " + tbContract.getSerial());
//                input = downloadFile(fileUrl);
            }
            String name = loan.getSerial() + ".pdf";
            // 目标文件名
            String dst = path + name;
            if (input != null) {
                sftpUploader.deploy(input, dst);
            }
            log.info("processLoan success, id : " + loan.getId());
        } catch (Exception e) {
            log.error("processLoan exception, id : " + loan.getId(), e);
        }
    }

    private InputStream downloadFile(String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(9 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            return inputStream;
        } catch (Exception e) {
            log.error("download from url exception,fileUrl:" + fileUrl, e);

        }
        return null;
    }

    private NosResponseDto getNosResponseDto(String applyNo) {
        String urlStr = "http://10.164.96.188:8181/task/getContract?applyNo=" + applyNo;
        try {
            //TODO Set Header: "User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"
            NosResponseDto responseDto = restTemplate.getForObject(urlStr, NosResponseDto.class);
            return responseDto;
        } catch (Exception e) {
            log.error("get nos response failed, applyNo: " + applyNo, e);
        }
        return new NosResponseDto().setSuccessed(false);
    }
}